<style lang="scss"></style>

<template>
  <div class="create-particular-date">
    <el-dialog :close-on-click-modal="false"
      title="编辑特殊日期"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="closeDialog"
    >
      <div v-loading="isLoading" class="body">
        <ParticularDateForm
          ref="form"
          v-model="form"
          :plans="plansFormatted"
          :fetch-plans-fn="getPatrolPlans"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="isActionDisabled"
          @click="closeDialog"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          :disabled="isActionDisabled"
          :loading="isSubmitting"
          @click="submit"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ParticularDateForm from './ParticularDateForm.vue'
import { particularDate, editParticularDate, patrolPlans } from '@/api/watchman'
import { atLeast } from '@/utils/kris_utils'
import dayjs from 'dayjs'
export default {
  components: {
    ParticularDateForm
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default: false
    },
    id: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      form: {
        date: null,
        plan: null
      },

      particularDate: null,
      plans: [],

      isLoading: false,
      isSubmitting: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('input', v)
      }
    },
    isActionDisabled() {
      const { isSubmitting, isLoading } = this
      return isSubmitting || isLoading
    },
    isShow() {
      return typeof this.id === 'number' && this.dialogVisible
    },
    plansFormatted() {
      return this.plans
      // if(!this.particularDate || !this.particularDate?.classes)return this.plans
      // let { id,name } = this.particularDate.classes,
      //     plans = [...this.plans,{label:name,value:id}],
      //     ids = plans.map(plan => plan.value),
      //     uniqueIds = [...new Set(ids)],
      //     result = uniqueIds.map(id => plans.find(item => item.value === id))

      // return result
    }
  },
  watch: {
    isShow(visible) {
      visible && this.initData()
    }
  },
  methods: {
    closeDialog() {
      if (this.isActionDisabled) return

      this.dialogVisible = false
    },
    async getPatrolPlans(kw) {
      const params = {
        name: kw,
        paginate:10000
      }

      const result = await patrolPlans(params)
      this.plans = result.data.map(plan => {
        const { id, name } = plan
        return {
          label: name,
          value: id
        }
      })
    },
    formDeserialization(data) {
      if (!atLeast(data, ['date', 'classes'])) return
      const plan = data.classes?.id ?? null
      this.form = {
        date: dayjs(data.date).toDate(),
        plan
      }
    },
    dateFormatter(date, format = 'YYYY-MM-DD') {
      return dayjs(date).format(format)
    },
    buildParams() {
      const { date, plan } = this.form
      return {
        id: this.id,
        date: this.dateFormatter(date),
        class_id: plan
      }
    },
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    async submit() {
      try {
        const flag = await this.$refs?.form.validate()
        if (!flag) return

        this.isSubmitting = true
        const params = this.buildParams()
        await this.sleep(300)
        const result = await editParticularDate(params)
        this.isSubmitting = false
        this.$emit('success', result)
      } catch (error) {
        this.$emit('fail', error)
        this.isSubmitting = false
      }
    },
    async getParticularDate() {
      const result = await particularDate(this.id)
      this.particularDate = result.data
      this.formDeserialization(result.data)
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getParticularDate(),
        this.getPatrolPlans()
      ])

      const failTasks = result.filter(task => task.status === 'rejected')
      if (failTasks.length <= 0) return

      throw failTasks.at(0).reason
    },
    async initData() {
      try {
        this.isLoading = true
        await this.loadData()
        this.isLoading = false
      } catch (error) {
        this.isLoading = false
      }
    }
  }
}
</script>
